<?php
class V
{
	private $width;//宽
	private $height;//高
	private $codeNum;//个数
	private $checkCode;//将产生的字符串保存在哪个成员属性当中
	private $img;//画布资源
	private $imgType;
	
	function __construct($width=120, $height=60, $codeNum=4, $imgType='png')
	{
		 $this->width = $width;
		 $this->height = $height;
		 $this->img = imagecreatetruecolor($this->width,$this->height);//产生画布
		 $this->codeNum = $codeNum;
		 $this->imgType = $imgType;
		 $this->checkCode = $this->createCheckCode();
	}
	
	//产生随机字随串
	private function createCheckCode(){
		$str='ABCDEFGHJKLMNPQRSTUVWXY3456789';
		$string = '';
		for($i = $this->codeNum; $i--;){
			$string .= $str[mt_rand(0, 29)];
			
		}
		return $_SESSION['auto_code'] = $string;
	}
	
	//随机颜色画布
	private function randBg(){
		return imagecolorallocate($this->img,rand(130,255),rand(130,255),rand(130,255));
	}
	
	//随机颜色字的
	private function randFont(){
		return imagecolorallocate($this->img,rand(0,120),rand(0,120),rand(0,120));
	}

	
	//干扰元素（点，线.......）
	private function randPix(){
		$area=ceil(($this->width*$this->height)/8);
		for($i=0;$i<$area;$i++){
			imagesetpixel($this->img,rand(0,$this->width),rand(0,$this->height),$this->randBg());
		}
	}
	
	//写字
	function createString(){
		for($i = $this->codeNum; $i--;){
			$x=ceil(($this->width) / $this->codeNum * $i + 10);
			$y=rand(5,$this->height-15);
			imagechar($this->img ,5 ,$x ,$y ,$this->checkCode[$i] ,$this->randFont());
			//用于解决字体不够大，需加载字体文件,否则不用。
			//$y=rand(28,$this->height-15);imagettftext($this->img , 22, 0,$x , $y, $this->randFont(), './simhei.ttf',$this->checkCode[$i]);
		}
	}
	//输出
	private function out(){
		$func='image'.$this->imgType;
		$string='content-type:image/'.$this->imgType;
		if(function_exists($func)){
				header($string);
				$func($this->img);
		}else{
			exit('当前环境不支持'.$this->imgType.'类型');
		}
		
	}
	private function createBg(){
		imagefilledrectangle($this->img,0,0,$this->width,$this->height,$this->randBg());
	}
	
	function getImg(){
		$this->createBg();
		$this->randPix();
		$this->createString();
		$this->out();
		
	}
	
	public function des(){
		imagedestroy($this->img);
	}
	
	function __get($proName){
		return $proName ==='checkCode' ? $this->checkCode : false;
	}
	//销毁
	function __destruct(){
		$this->des();
	}
}
$autoCode = new V;
$autoCode->getImg();